#!/usr/bin/env python3
"""
头像获取辅助函数
用于从URL获取base64编码的头像数据
"""

import requests
import base64
from typing import Optional
from io import BytesIO

def get_avatar_base64_from_url(url: str) -> Optional[str]:
    """
    从URL获取头像并转换为base64编码
    
    Args:
        url: 头像URL
        
    Returns:
        base64编码的图片数据，失败时返回None
    """
    if not url or not url.strip():
        return None
        
    try:
        # 设置请求头，模拟浏览器访问
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        response = requests.get(url, headers=headers, timeout=10)
        if response.status_code == 200:
            image_data = response.content
            # 检查是否为有效的图片数据
            if len(image_data) > 0:
                return base64.b64encode(image_data).decode('utf-8')
        
        return None
        
    except Exception as e:
        print(f"获取头像失败 {url}: {e}")
        return None

async def get_avatar_base64_from_url_async(url: str) -> Optional[str]:
    """
    异步版本：从URL获取头像并转换为base64编码
    
    Args:
        url: 头像URL
        
    Returns:
        base64编码的图片数据，失败时返回None
    """
    if not url or not url.strip():
        return None
        
    try:
        import aiohttp
        
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as response:
                if response.status == 200:
                    image_data = await response.read()
                    if len(image_data) > 0:
                        return base64.b64encode(image_data).decode('utf-8')
        
        return None
        
    except ImportError:
        # 如果没有aiohttp，回退到同步版本
        return get_avatar_base64_from_url(url)
    except Exception as e:
        print(f"获取头像失败 {url}: {e}")
        return None